﻿/**********************************************************************************
 * 程序说明：     页面广告类(数据访问层)
 * 创建日期：     2009.6.13
 * 修改日期：     2012.02.15
 * 程序制作：     agui
 * 联系方式：     mailto:354990393@qq.com  
 * ********************************************************************************/
using System;
using System.Collections.Generic;
using System.Text;
using System.Data;

using PlugNT.Safe;
using PlugNT.Database;
using PlugNT.Database.Common.Simple;
using PlugNT.Custom;
using PlugNT.Cms.Model;

namespace PlugNT.Cms.DAL
{
    /// <summary>
    /// 页面广告类
    /// </summary>
    public class Ad
    {

        private static string currTableName = WebConfig.TablePrefix + "ad";
        private static Dictionary<string, string> adlinks;

        static Ad()
        {
            adlinks = new Dictionary<string, string>();
        }


        private int GetClassId(int id)
        {
            string sql = "Select top 1 [class_id] From " + currTableName + " where [id]=" + id.ToString();
            object obj = DbHelper.GetSingle(sql);
            return (obj == null) ? 0 : int.Parse(obj.ToString());
        }

        /// <summary>
        /// 得到一组广告
        /// </summary>
        private string GetAdLinks(int classId)
        {
            StringBuilder sb = new StringBuilder();
            IDataReader dr = GetReader(1,"[code]"," and class_id=" + classId);
            if (dr!=null)
            {
                while(dr.Read())
                {
                    sb.AppendLine();
                    sb.AppendLine(dr["code"].ToString());
                }
                dr.Close();
            }
            return sb.ToString();
        }


        /// <summary>
        /// 创建一个页面的广告(由多个广告对象组成)
        /// </summary>
        /// <param name="no"></param>
        /// <param name="splitstr"></param> 
        /// <returns></returns>
        public string CreateAdLinks(int classId)
        {
            string reString = "";
            if (!adlinks.TryGetValue(classId.ToString(), out reString))
            {
                reString = GetAdLinks(classId);
                if (reString != "")   
                {
                    adlinks.Add(classId.ToString(), reString);
                }
            }
            return reString;
        }

        /// <summary>
        /// 删除所有的广告
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        public void RemoveAdLinks()
        {
            adlinks.Clear();
        }

        /// <summary>
        /// 删除一个页面的广告
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        public static bool RemoveAdLinks(int classId)
        {
            bool flag = false;
            if (adlinks.ContainsKey(classId.ToString()))
            {
                flag = adlinks.Remove(classId.ToString());
            }
            return flag;
        }



        /// <summary>
        /// 得到模型
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        public AdInfo GetAdInfo(int id)
        {
            AdInfo model = null;
            IDataReader dr = GetReader(1,"*", " and id=" + id);
            if (dr != null)
            {
                if (dr.Read())
                {
                    model = new AdInfo();
                    model.id = int.Parse(dr["id"].ToString());
                    model.no = dr["no"].ToString();
                    model.class_id = int.Parse(dr["class_id"].ToString());
                    model.target_url = dr["target_url"].ToString();
                    model.description = dr["description"].ToString();
                    model.start_time = DateTime.Parse(dr["start_time"].ToString());
                    model.end_time = DateTime.Parse(dr["end_time"].ToString());
                    model.code = dr["code"].ToString();
                    model.file_path = dr["file_path"].ToString();
                    model.target_html_id = dr["target_html_id"].ToString();
                    model.type = int.Parse(dr["type"].ToString());
                    model.width = int.Parse(dr["width"].ToString());
                    model.height = int.Parse(dr["height"].ToString());
                    model.disabled = dr["disabled"].ToString() == "1";
                    model.order = int.Parse(dr["order"].ToString());
                }
                dr.Close();
            }
            return model;
        }





        #region 添加，修改，删除操作

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Add(AdInfo model)
        {

            RemoveAdLinks(model.class_id); 

            StringBuilder strSql = new StringBuilder();
            strSql.Append("insert into " + currTableName);
            strSql.Append(" ([no],[class_id],[target_url],[description],[start_time],[end_time],");
            strSql.Append("code,file_path,target_html_id,type,width,height,disabled,");
            strSql.Append("[order]) ");
            strSql.Append(" values (");
            strSql.Append("'" + StringHelper.SqlFilter(model.no) + "',");
            strSql.Append(" " + model.class_id.ToString() + ",");
            strSql.Append("'" + StringHelper.SqlFilter(model.target_url) + "',");
            strSql.Append("'" + StringHelper.SqlFilter(model.description) + "',");
            strSql.Append("'" + model.start_time.ToString() + "',");
            strSql.Append("'" + model.end_time.ToString() + "',");
            strSql.Append("'" + StringHelper.SqlFilter(model.code) + "',");
            strSql.Append("'" + StringHelper.SqlFilter(model.file_path) + "',");
            strSql.Append("'" + StringHelper.SqlFilter(model.target_html_id) + "',");
            strSql.Append(" " + model.type.ToString() + ",");
            strSql.Append(" " + model.width.ToString() + ",");
            strSql.Append(" " + model.height.ToString() + ",");
            strSql.Append(" " + (model.disabled ? "1" : "0") + ",");

            strSql.Append(" " + model.order.ToString());
            strSql.Append(")");

            //System.Web.HttpContext.Current.Response.Write(strSql.ToString());

            return (DbHelper.ExecuteSql(strSql.ToString()) > 0) ? true : false;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        public bool Update(AdInfo model)
        {
            int cid1 = model.class_id;
            int cid2 = GetClassId(model.id);
            //删除页面中的广告
            if (cid1 != cid2)
            {
                RemoveAdLinks(cid1);
                RemoveAdLinks(cid2);
            }
            else
            {
                RemoveAdLinks(cid1);
            }

            StringBuilder strSql = new StringBuilder();
            strSql.Append("update " + currTableName);
            strSql.Append(" set [class_id]=" + model.class_id + ",");
            strSql.Append("[target_url]='" + StringHelper.SqlFilter(model.target_url) + "',");
            strSql.Append("[description]='" + StringHelper.SqlFilter(model.description) + "',");
            strSql.Append("[start_time]='" + model.start_time.ToString() + "',");
            strSql.Append("[end_time]='" + model.end_time.ToString() + "',");
            strSql.Append("[code]='" + StringHelper.SqlFilter(model.code) + "',");
            strSql.Append("[file_path]='" + StringHelper.SqlFilter(model.file_path) + "',");
            strSql.Append("[target_html_id]='" + StringHelper.SqlFilter(model.target_html_id) + "',");
            strSql.Append("[type]=" + model.type.ToString() + ",");
            strSql.Append("[width]=" + model.width.ToString() + ",");
            strSql.Append("[height]=" + model.height.ToString() + ",");
            strSql.Append("[disabled]=" + (model.disabled ? "1" : "0") + ",");
            strSql.Append("[order]=" + model.order.ToString());
            strSql.Append(" where id=" + model.id.ToString());

            return (DbHelper.ExecuteSql(strSql.ToString()) > 0) ? true : false;
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public bool Delete(int id)
        {
            RemoveAdLinks(GetClassId(id)); 

            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete From " + currTableName);
            strSql.Append(" where [id]="+id.ToString());
            return (DbHelper.ExecuteSql(strSql.ToString()) > 0) ? true : false;
        }

        /// <summary>
        /// 删除多个
        /// </summary>
        /// <param name="no"></param>
        /// <returns></returns>
        public bool DeleteByClassId(int classId)
        {
            RemoveAdLinks(classId); 
            StringBuilder strSql = new StringBuilder();
            strSql.Append("delete From " + currTableName);
            strSql.Append(" where class_id= " + classId);
            return (DbHelper.ExecuteSql(strSql.ToString()) > 0) ? true : false;
        }
        #endregion


        #region 获取列表

        /// <summary>
        /// 得到IDataReader
        /// </summary>
        /// <param name="topCount">-1表示全部</param>
        /// <param name="colNames"></param>
        /// <param name="andWhere"></param>
        /// <returns></returns>
        public IDataReader GetReader(int topCount, string colNames, string andWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select " + (topCount == -1 ? "" : "top " + topCount) + " " + colNames + " from " + currTableName + " where 1=1 " + andWhere);
            strSql.Append(WebConfig.IsAccess ? " order by [order] desc" : " order by [order],id desc");
            return DbHelper.ExecuteReader(strSql.ToString());
        }

        public DataTable GetList(string andWhere)
        {
            StringBuilder strSql = new StringBuilder();
            strSql.Append("select * from " + currTableName + " where 1=1 " + andWhere);
            strSql.Append(WebConfig.IsAccess ? " order by [order] desc" : " order by [order],id desc");
            return DbHelper.GetDataTable(strSql.ToString());
        }

        public DataTable GetList(int topCount, int currPageCount, string andWhere)
        {
            string sql = Sql.GetRePagingString(topCount, currPageCount, currTableName, "id", andWhere);
            return DbHelper.GetDataTable(sql);
        }

        public DataTable GetList(int topCount, int currPageCount, string andWhere,LeftJoinInfo joininfo)
        {
            string sql = Sql.GetRePagingString(topCount, currPageCount, currTableName, "id", "*", andWhere, joininfo);
            return DbHelper.GetDataTable(sql);
        }

        public int GetCount(string andWhere)
        {
            string sql = "select count(1) from [" + currTableName + "] where 1=1 " + andWhere;
            return (int)DbHelper.GetSingle(sql);
        }

        #endregion
    }
}
